'use client';
import Container from '@/components/Container';
import ResultCard from '@/components/ResultCard';
import { drawRandom, drawWithExclusions } from '@/lib/random';
import { useAppStore } from '@/store';
import { useNearbyRestaurants } from '@/hooks/useNearbyRestaurants';
import type { Restaurant } from '@/lib/types';
import { useEffect, useState, Suspense, useCallback, useRef } from 'react';
import { useSearchParams } from 'next/navigation';

function ResultContent() {
  const params = useSearchParams();
  const mode = (params.get('mode') ?? 'random') as 'random' | 'exclude';
  const selectedCuisines = useAppStore((state) => state.selectedCuisines);
  const redrawTrigger = useAppStore((state) => state.redrawTrigger);

  const [current, setCurrent] = useState<Restaurant | null>(null);

  // 使用新的位置搜索Hook
  const {
    restaurants: pool,
    loading,
    error: locationError,
    hasLocation,
    requestLocation,
    searchNearby,
  } = useNearbyRestaurants({ autoFetch: true });

  // 创建一个ref来跟踪上一次的redrawTrigger值
  const prevRedrawTrigger = useRef(redrawTrigger);

  // 提取随机化逻辑到一个共享函数
  const getRandomRestaurant = useCallback(() => {
    if (pool.length === 0) return null;
    return mode === 'exclude' ? drawWithExclusions(pool, selectedCuisines) : drawRandom(pool);
  }, [pool, mode, selectedCuisines]);

  // 当餐厅池更新时，重新抽取餐厅
  useEffect(() => {
    if (pool.length > 0) {
      setCurrent(getRandomRestaurant());
    }
  }, [pool, getRandomRestaurant]);

  // 当 redrawTrigger 变化时，重新抽取餐厅
  useEffect(() => {
    if (pool.length > 0 && redrawTrigger > prevRedrawTrigger.current) {
      setCurrent(getRandomRestaurant());
    }
    prevRedrawTrigger.current = redrawTrigger;
  }, [redrawTrigger, pool, getRandomRestaurant]);

  const redraw = useCallback(() => {
    if (pool.length > 0) {
      setCurrent(getRandomRestaurant());
    }
  }, [getRandomRestaurant, pool.length]);

  const accept = useCallback(() => {
    if (!current) return;
    const target = current.detailUrl ?? current.mapUrl;
    if (target) window.open(target, '_blank', 'noopener,noreferrer');
  }, [current]);

  if (loading) {
    return (
      <div className="space-y-4">
        <h1 className="text-xl font-semibold">随机结果</h1>
        <div className="flex flex-col items-center justify-center h-64 space-y-4">
          <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-foreground"></div>
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {hasLocation ? '正在搜索周边餐厅...' : '正在获取位置信息...'}
          </p>
        </div>
      </div>
    );
  }

  if (locationError) {
    return (
      <div className="space-y-4">
        <h1 className="text-xl font-semibold">随机结果</h1>
        <div className="flex flex-col items-center justify-center h-64 space-y-4">
          <p className="text-sm text-red-600 dark:text-red-400 text-center">{locationError}</p>
          <button
            onClick={requestLocation}
            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
          >
            重新获取位置
          </button>
          <button
            onClick={searchNearby}
            className="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
          >
            使用默认数据
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">随机结果</h1>
        {hasLocation && (
          <span className="text-xs text-green-600 dark:text-green-400 px-2 py-1 rounded-full bg-green-100 dark:bg-green-900">
            基于当前位置
          </span>
        )}
      </div>
      {!current && pool.length === 0 && (
        <p className="text-sm">未能找到符合条件的餐厅，请尝试调整筛选条件</p>
      )}
      {!current && pool.length > 0 && (
        <p className="text-sm">未能找到符合筛选条件的餐厅，请尝试调整筛选条件</p>
      )}
      {current && <ResultCard restaurant={current} onDislike={redraw} onAccept={accept} />}
    </div>
  );
}

export default function ResultPage() {
  return (
    <Container>
      <Suspense
        fallback={
          <div className="space-y-4">
            <h1 className="text-xl font-semibold">随机结果</h1>
            <div className="flex items-center justify-center h-64">
              <div className="animate-pulse text-sm">正在加载...</div>
            </div>
          </div>
        }
      >
        <ResultContent />
      </Suspense>
    </Container>
  );
}
